/**
 * 同行同住分析器
 * 检测共同入住酒店或同乘交通工具的密切关系人
 */
class CoTravelAnalyzer extends BaseAnalyzer {
    constructor(caseId) {
        super(caseId);
        this.name = '同行同住';
        this.description = '检测共同入住酒店或同乘交通工具的记录，发现密切关系人';
    }

    /**
     * 执行同行同住分析
     * @param {Object} params { minOccurrences: 1 }
     */
    async analyze(params = {}) {
        const minOccurrences = params.minOccurrences || 1;

        // 同住分析 SQL
        const sqlCoHabitation = `
      SELECT 
        hotel_name,
        date(check_in_time) as check_date,
        COUNT(DISTINCT guest_name) as guest_count,
        GROUP_CONCAT(DISTINCT guest_name) as guests,
        MIN(check_in_time) as first_check_in,
        MAX(check_out_time) as last_check_out
      FROM accommodation_records
      WHERE case_id = ? 
        AND guest_name IS NOT NULL 
        AND guest_name != ''
      GROUP BY hotel_name, check_date
      HAVING guest_count > 1
      ORDER BY guest_count DESC, check_date DESC
      LIMIT 100
    `;

        // 同行分析 SQL (暂未实现完全的同行逻辑，先基于同一车次/航班简单匹配)
        // 实际同行需要更复杂的逻辑：同车次 + 座位相邻 或 同航班 + 临近座位
        // 这里先实现简单的同车次/航班匹配
        const sqlCoTravel = `
      SELECT 
        transport_type,
        train_number as transport_number, -- 借用列名，实际可能是航班号
        date(start_time) as travel_date,
        COUNT(*) as passenger_count,
        GROUP_CONCAT(destination) as destinations
      FROM travel_records
      WHERE case_id = ?
      GROUP BY transport_type, transport_number, travel_date
      HAVING passenger_count > 1
      ORDER BY passenger_count DESC
      LIMIT 50
    `;

        const resultCoHabitation = await this.runQuery(sqlCoHabitation, [this.caseId]);
        // const resultCoTravel = await this.runQuery(sqlCoTravel, [this.caseId]); // 暂时先只做同住

        if (!resultCoHabitation.success) {
            return this.createResult('co_travel', this.name, [], '查询失败: ' + resultCoHabitation.message, 'danger');
        }

        const data = resultCoHabitation.data;
        const summary = data.length > 0
            ? `发现 ${data.length} 次多人同住记录，涉及 ${this.countUniqueGuests(data)} 名人员`
            : '未发现同行同住记录';

        const level = data.length > 5 ? 'warning' : (data.length > 0 ? 'info' : 'info');

        return this.createResult('co_travel', this.name, data, summary, level);
    }

    countUniqueGuests(data) {
        const guests = new Set();
        data.forEach(row => {
            if (row.guests) {
                row.guests.split(',').forEach(g => guests.add(g));
            }
        });
        return guests.size;
    }

    renderResult(data) {
        if (!data || data.length === 0) {
            return '<div class="empty-result" style="padding:40px; text-align:center; color:#999;">✓ 未发现同行同住记录</div>';
        }

        let html = `
      <div class="result-summary" style="padding:15px; background:#e1f3d8; border-left:4px solid #67c23a; margin-bottom:15px;">
        <strong>🏨 发现 ${data.length} 次同住记录</strong>
        <p style="margin:5px 0 0; font-size:0.9rem;">这些记录显示多人同一天入住同一酒店，可能存在密切关系</p>
      </div>
      
      <table class="analysis-result-table" style="width:100%; border-collapse:collapse; font-size:0.9rem;">
        <thead style="background:#f5f7fa;">
          <tr>
            <th style="padding:10px; border:1px solid #e0e0e0;">酒店名称</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">入住日期</th>
            <th style="padding:10px; border:1px solid #e0e0e0; text-align:center;">同住人数</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">人员名单</th>
            <th style="padding:10px; border:1px solid #e0e0e0;">时间段</th>
          </tr>
        </thead>
        <tbody>
    `;

        data.forEach((row, index) => {
            const rowStyle = index % 2 === 0 ? 'background:#fafafa;' : '';
            html += `<tr style="${rowStyle}">`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.hotel_name || '-'}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center;">${row.check_date || '-'}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; text-align:center; font-weight:bold; color:#F56C6C;">${row.guest_count}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0;">${row.guests || '-'}</td>`;
            html += `<td style="padding:8px; border:1px solid #e0e0e0; font-size:0.85rem;">${this.formatDate(row.first_check_in)} ~ ${this.formatDate(row.last_check_out)}</td>`;
            html += '</tr>';
        });

        html += '</tbody></table>';
        return html;
    }
}

window.CoTravelAnalyzer = CoTravelAnalyzer;
